package cn.fu.validato.controller;


import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.fu.validato.model.User;
import cn.fu.validato.rule.InspectorException;
/**
 * 
* @ClassName: TestController 
* @Description: 测试注解校验
* @author zhangxiaofu
* @date 2016年5月28日 下午10:01:44 
*
 */
@Controller
public class TestController 
{
	/**
	 * 
	* @Title: formSubmit 
	* @Description: 表单提交
	* @param @param user
	* @param @param result
	* @param @return
	* @param @throws InspectorException    设定文件 
	* @return ModelAndView    返回类型 
	* @throws
	 */
	@RequestMapping("/formSubmit")
	public ModelAndView formSubmit(@Valid User user,BindingResult result) throws InspectorException {
		if(result.hasErrors()){
//			StringBuffer sb = new StringBuffer("<br/>");
//			for(FieldError fieldError :result.getFieldErrors()){
//				sb.append(fieldError.getDefaultMessage());//错误消息
//				sb.append("错误字段："+fieldError.getField()+"<br/>"+" 值 ：" +fieldError.getRejectedValue()+"<br/>");
//				
//				通过异常方法，抛出校验错误信息
				throwInspectorException(result);
//			}
//			ModelAndView mav = new ModelAndView();
//	    	mav.setViewName("error.jsp");
//	    	mav.addObject("msg","<br/>后台校验出现错误："+sb);
//	    	return mav;
		}
		return null;
	}
	
	/**
	 * 
	* @Title: throwInspectorException 
	* @Description: 通过异常抛出校验错误 
	* @param @param result
	* @param @throws InspectorException    设定文件 
	* @return void    返回类型 
	* @throws
	 */
    private void throwInspectorException(BindingResult result) throws InspectorException {
        StringBuffer sb = new StringBuffer("<br/>");
        for(FieldError fieldError :result.getFieldErrors()){
        	sb.append(fieldError.getDefaultMessage());//错误消息
            sb.append("错误字段："+fieldError.getField()+"<br/>"+" 值 ：" +fieldError.getRejectedValue()+"<br/>");
        }
        throw new InspectorException(sb+"");
	}

	
    /**
     * 
    * @Title: inspector 
    * @Description: 捕获校验异常
    * @param @param e
    * @param @param request
    * @param @return    设定文件 
    * @return ModelAndView    返回类型 
    * @throws
     */
    @ExceptionHandler(InspectorException.class)  
    public ModelAndView inspector(InspectorException e,HttpServletRequest request){ 
    	ModelAndView mav = new ModelAndView();
    	mav.setViewName("error.jsp");
    	mav.addObject("msg","<br/>后台校验出现错误："+e.getMessage());
    	
		return mav;
    } 
    

}
